package com.abocode.aichat.messenger.application;

import com.abocode.aichat.data.Entity;
import com.abocode.aichat.server.context.pipeline.UserOnlinePipeline;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author guanxf
 */
@Service("channelOnlinePipeline")
public class RedisUserOnlinePipelineImpl implements UserOnlinePipeline {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean isOnline(Entity entity) {
        String onlineKey = RedisKeyHolder.ONLINE_MEMBERS_PREFIX + entity.getNode();
        return redisTemplate.hasKey(onlineKey);
    }
    @Override
    public String domain(Entity entity) {
        String onlineKey = RedisKeyHolder.ONLINE_MEMBERS_PREFIX + entity.getNode();
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(onlineKey);
        Object d=boundHashOperations.get("domain");
        if(d==null){
            return null;
        }else{
            return String.valueOf(d);
        }
    }

    @Override
    public void presence(Entity entity) {
        String onlineKey = RedisKeyHolder.ONLINE_MEMBERS_PREFIX + entity.getNode();
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(onlineKey);
        boundHashOperations.put("presence", entity.getPresence());
        boundHashOperations.put("jid", entity.getFullName());
        boundHashOperations.put("domain", entity.getDomain());
        if(entity.isResourceSet()){
            boundHashOperations.put("os", entity.getResource());
        }

    }

    @Override
    public void offline(Entity entity) {
        String onlineKey = RedisKeyHolder.ONLINE_MEMBERS_PREFIX + entity.getNode();
        redisTemplate.delete(onlineKey);
    }
}
